package com.google.code.jbauble.mvc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.google.code.jbauble.mvc.support.WebLoader;

public class WebContext {
	private static WebContext context;
	
	private WebContext() {
		
	}
	
	public static void init(DefaultConfiguration conf) {
		WebContext wc = getInstance();
		wc.setConfig(conf);
		
		wc.initContext(conf);
	}

	public static WebContext getInstance() {
		if (context != null)
			return context;
		
		context = new WebContext();
		return context;
	}
	
	private DefaultConfiguration config;
	private ApplicationContext springContext = null;

	private void initContext(DefaultConfiguration conf) {
		String springConfig = config.getProperty(DefaultConfiguration.SERVICE_SPRING);
		if (springConfig != null && !springConfig.equals("")) {
			springContext = new FileSystemXmlApplicationContext(
					WebLoader.mergePath(System.getProperty(DefaultConfiguration.WEB_CONF_PATH), springConfig));
		}
	}
	
	public DefaultConfiguration getConfig() {
		return config;
	}

	public void setConfig(DefaultConfiguration config) {
		this.config = config;
	}
	
	public Object getBean(String name) {
		return springContext.getBean(name);
	}
	
	public Object getBean(Class clazz) {
		return springContext.getBean(clazz);
	}
}
